package net.skyaims.aiolia.chat.litp;

import net.skyaims.aiolia.chat.core.Platform;
import net.skyaims.aiolia.chat.litp.LitpOption.Entry;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public abstract class LitpDock extends Platform<LitpOption, LitpEnvironment> {

    private static final Logger log = LoggerFactory.getLogger(LitpDock.class);

    private static final String[] litpArgs = new String[]{"litp_instance", "litp.conf.properties"};

    private ServerBootstrap dock;

    public LitpDock() {
        super(litpArgs[0], litpArgs[1]);
        // TODO Auto-generated constructor stub
    }

    public LitpDock(String instanceName, String optionFile) {
        super(instanceName, optionFile);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void service(LitpOption opt, LitpEnvironment env) throws Exception {
        // TODO Auto-generated method stub
        log.info("Invoke {} Serivce", env.getInstanceName());
        int threadCount = Runtime.getRuntime().availableProcessors();
        Executor boss = Executors.newFixedThreadPool(threadCount);
        Executor work = Executors.newFixedThreadPool(threadCount * 2);
        dock = new ServerBootstrap(new NioServerSocketChannelFactory(boss, work, threadCount * 2));
        dock.setOption(Entry.KEEP_ALIVE.getKey(), Entry.KEEP_ALIVE.getValue());
        dock.setOption(Entry.TCP_NO_DELAY.getKey(), Entry.TCP_NO_DELAY.getValue());
        dock.setPipelineFactory(new LitpChannelPipelineFactory());
        dock.bind(new InetSocketAddress(opt.getPort()));
    }

    @Override
    protected LitpOption loadOpt(String optionFile) {
        // TODO Auto-generated method stub
        LitpOption opt = new LitpOption();
        opt.setPath(optionFile);
        return opt;
    }

    @Override
    protected LitpEnvironment loadEnv(String instanceName) {
        // TODO Auto-generated method stub
        LitpEnvironment env = new LitpEnvironment();
        env.setInstanceName(instanceName);
        return env;
    }

}
